package com.uni.service.impl;

import com.uni.dao.ProdtypeMapper;
import com.uni.dao.ProductMapper;
import com.uni.dao.ProductProviderMapper;
import com.uni.pojo.*;
import com.uni.service.ProductService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProdtypeMapper prodtypeMapper;
    @Autowired
    ProductProviderMapper productProviderMapper;
    @Override
    public List<Product> getAllProduct() {
        return productMapper.selectByExampleWithBLOBs(new ProductExample());
    }

    @Override
    public List<Product> getProductWithProviderBySome(Map<String, String> paramMap) {
        return productMapper.selectProductWithProviderBySome(paramMap);
    }
    @Override
    public List<Product> getProductWithTypeBySome(Map<String, String> paramMap) {
        return productMapper.selectProductWithTypeBySome(paramMap);
    }
    @Override
    public Product getProductWithProviderById(Long id) {
        return productMapper.selectWithProviderAndTypeById(id);
    }

    @Override
    public List<Prodtype> getAllProdType() {
        return prodtypeMapper.selectByExample(new ProdtypeExample());
    }

    @Override
    public int modifyProductById(Product product) {
        int i = 0;
        i += productMapper.updateByPrimaryKeySelective(product);
        i += productProviderMapper.updateProductProvider(product);
        return i;
    }

    @Override
    public int takeItDown(Long prodId) {
        return productMapper.updateToDown(prodId);
    }

    @Override
    public int takeItUp(Long prodId) {
        return productMapper.updateToUp(prodId);
    }

    @Override
    public int takeThemDown(List<Long> prodId) {
        return productMapper.updateToDowns(prodId);
    }

    @Override
    public int takeThemUp(List<Long> prodId) {
        return productMapper.updateToUps(prodId);
    }

    @Override
    public Product addProduct(Product product) {
        // 插入商品表
        int i = productMapper.insertSelective(product);
        Product prod = null;
        // 插入商品-供应商中间表
        if(i == 1) {
            // 插入后查询该商品的ID
            prod = productMapper.selectProductByName(product.getName());
            ProductProvider productProvider = new ProductProvider(prod.getId(), product.getProvider().getId());
            i += productProviderMapper.insertSelective(productProvider);
            // 插入商品-类型中间表
            if(i == 2){
                prodtypeMapper.insertByProductAndProdtype(prod, product.getProdtype());
            }
        }
        return prod;
    }
}
